# -*- coding: utf-8 -*
import os, sys, re, xbmc, xbmcgui, string, time, urllib, urllib2, cookielib
subtitles_list=[]
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
	if len(tvshow) > 0:
		episode = ("%.2d" % int(episode))
		params = urllib.urlencode({'arama': tvshow, 'src_select': '/index.php?page=arama'})
		search_url = urllib.urlopen("http://divxplanet.com/index.php?page=arama", params)
		ilk_link = re.findall("<td width=15%><a href=\"(.*?)\" target=\"_top\"", search_url.read())
		ilk_link = "http://www.divxplanet.com" + ilk_link[0]
		ikinci_url = urllib.urlopen(ilk_link)
		altyazilar = re.findall("\"(/sub/s.*?)\" title=.*?/images/bayraklar/(.*?)\.gif.*?Sezon : <b>(.*?)</b> B.l.m : <b>(.*?)</b></div></td>.*?<td colspan=\"3\">(.*?)</td>",ikinci_url.read(), re.DOTALL)
		for altyazi in altyazilar:
			link = "http://divxplanet.com" + altyazi[0]
			if altyazi[1].strip() == "turkey":
				languageshort = "tr"
				languagelong = "Turkish"
			elif altyazi[1].strip() == "england":
				languageshort = "en"
				languagelong = "English"
			else:
				languageshort = "-"
				languagelong = "Other"
			sezon = altyazi[2]
			bolum = altyazi[3]
			filename = altyazi[4]
			id = 1
			if bolum == "Paket":
				if sezon is season:
					subtitles_list.append({'rating': '0', 'no_files': 1, 'filename': "Paket " + filename, 'link': link, 'sync': False, 'id' : id, 'language_flag': 'flags/' + languageshort + '.gif', 'language_name': languagelong})
			else:
				if sezon is season and bolum == episode:
					subtitles_list.append({'rating': '0', 'no_files': 1, 'filename': filename, 'link': link, 'sync': False, 'id' : id, 'language_flag': 'flags/' + languageshort + '.gif', 'language_name': languagelong})
		
	else:
		if len(year) > 0:
			title = (title + " " + str(year))
		params = urllib.urlencode({'arama': title, 'src_select': '/index.php?page=arama'})
		search_url = urllib.urlopen("http://divxplanet.com/index.php?page=arama", params)
		ilk_link = re.findall("<td width=15%><a href=\"(.*?)\" target=\"_top\"", search_url.read())
		ilk_link = "http://www.divxplanet.com" + ilk_link[0]
		ikinci_url = urllib.urlopen(ilk_link)
		altyazilar = re.findall("\"(/sub/s.*?)\" title=.*?/images/bayraklar/(.*?)\.gif.*?<td colspan=\"3\">(.*?)</td>",ikinci_url.read(), re.DOTALL)
		for altyazi in altyazilar:
			link = "http://divxplanet.com" + altyazi[0]
			if altyazi[1].strip() == "turkey":
				languageshort = "tr"
				languagelong = "Turkish"
			elif altyazi[1].strip() == "england":
				languageshort = "en"
				languagelong = "English"
			else:
				languageshort = "-"
				languagelong = "Other"
			filename = altyazi[2]
			subtitles_list.append({'rating': '0', 'no_files': 1, 'filename': filename, 'link': link, 'sync': False, 'id' : 1, 'language_flag': 'flags/' + languageshort + '.gif', 'language_name': languagelong})
	return subtitles_list, "", "" #standard output

def download_subtitles (subtitles_list, pos, zip_subs, tmp_sub_dir, sub_folder, session_id): #standard input
	language = subtitles_list[pos][ "language_name" ]
	link = subtitles_list[pos][ "link" ]
	link2 = urllib2.urlopen(link)
	altyazi = re.findall("postc\" value=\"(.*?)\">.*?id\" value=\"(.*?)\">",link2.read(), re.DOTALL)
	params = urllib.urlencode({'postc': altyazi[0][0], 'id': altyazi[0][1]})
	url = "http://divxplanet.com/indir.php"
	request = urllib2.Request(url, params)
	cookies = cookielib.CookieJar()
	cookies.extract_cookies(link2,request)
	cookie_handler= urllib2.HTTPCookieProcessor( cookies )
	opener = urllib2.build_opener(cookie_handler)
	content = opener.open(request)
	local_tmp_file = os.path.join(tmp_sub_dir, "argenteam.rar")

	local_file_handle = open(local_tmp_file, "wb")
	local_file_handle.write(content.read())
	local_file_handle.close()

	files = os.listdir(tmp_sub_dir)
	init_filecount = len(files)
	filecount = init_filecount
	max_mtime = 0
	# determine the newest file from tmp_sub_dir
	for file in files:
		if (string.split(file,'.')[-1] in ['srt','sub','txt']):
			mtime = os.stat(os.path.join(tmp_sub_dir, file)).st_mtime
			if mtime > max_mtime:
				max_mtime =  mtime
		init_max_mtime = max_mtime
		time.sleep(2)  # wait 2 seconds so that the unpacked files are at least 1 second newer
		xbmc.executebuiltin("XBMC.Extract(" + local_tmp_file + "," + tmp_sub_dir +")")
		waittime  = 0
		while (filecount == init_filecount) and (waittime < 20) and (init_max_mtime == max_mtime): # nothing yet extracted
			time.sleep(1)  # wait 1 second to let the builtin function 'XBMC.extract' unpack
			files = os.listdir(tmp_sub_dir)
			filecount = len(files)
			# determine if there is a newer file created in tmp_sub_dir (marks that the extraction had completed)
			for file in files:
				if (string.split(file,'.')[-1] in ['srt','sub','txt']):
					mtime = os.stat(os.path.join(tmp_sub_dir, file)).st_mtime
					if (mtime > max_mtime):
						max_mtime =  mtime
			waittime  = waittime + 1
		for file in files:
			# there could be more subtitle files in tmp_sub_dir, so make sure we get the newly created subtitle file
			if (string.split(file, '.')[-1] in ['srt', 'sub', 'txt']) and (os.stat(os.path.join(tmp_sub_dir, file)).st_mtime > init_max_mtime): # unpacked file is a newly created subtitle file
				subs_file = os.path.join(tmp_sub_dir, file)
	return False, language, subs_file #standard output